package com.liuqi.openai.core.merge;

import com.liuqi.openai.core.completion.CompletionChoice;
import com.liuqi.openai.core.completion.CompletionResponse;
import java.util.ArrayList;
import java.util.List;

/**
 * @author liuqi
 * @date 2025/8/6
 **/
public class MergeChunkCompletion<Response extends CompletionResponse> extends MergeChunk<Response> {

    @Override
    public void merge(CompletionResponse response) {
        // 设置id、created、model、object、usage
        setCommon(response.getId(), response.getCreated(), response.getModel(), response.getObject(), response.getUsage());

        List<CompletionChoice> choices = response.getChoices();
        if (choices != null && !choices.isEmpty()) {
            choices.forEach(choice -> {
                appendContent(choice.getIndex(), choice.getText());
                setFinishReason(choice.getIndex(), choice.getFinishReason());
            });
        }
    }

    @Override
    public Response getResult() {
        return (Response) CompletionResponse.builder()
                .id(id)
                .created(created)
                .model(model)
                .object(object)
                .usage(usage)
                .choices(buildCompletionChoice())
                .build();

    }

    private List<CompletionChoice> buildCompletionChoice() {
        if (contentBuff == null) {
            return null;
        }
        List<CompletionChoice> completionChoices = new ArrayList<>(contentBuff.size());
        for (int i = 0; i < contentBuff.size(); i++) {
            completionChoices.add(CompletionChoice.builder()
                    .index(i)
                    .text(getContent(i))
                    .finishReason(getFinishReason(i))
                    .build()
            );
        }

        return completionChoices;
    }

}
